package com.ruoyi.resume.service.impl;

import com.ruoyi.resume.domain.model.resumeProfile.InternshipExperience;
import com.ruoyi.resume.domain.model.Tag;
import com.ruoyi.resume.domain.model.resumeProfile.WorkExperience;
import com.ruoyi.resume.domain.request.LabelingRequest;
import com.ruoyi.resume.exception.InvalidParameterException;
import com.ruoyi.resume.service.ExperienceLabelingService;
import com.ruoyi.resume.utils.LabelingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.YearMonth;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExperienceLabelingServiceImpl implements ExperienceLabelingService {

    @Autowired
    private LabelingUtils labelingUtils;

    @Override
    public List<Map<String, Integer>> processEmploymentStatusRequest(LabelingRequest request) {
        validateRequest(request);

        List<YearMonth> workEndTimeList = request.getSplitResumeResult().getWorkExperiences() != null ?
                request.getSplitResumeResult().getWorkExperiences().stream()
                        .map(WorkExperience::getEndTime)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList()) : Collections.emptyList();

        List<YearMonth> internshipEndTimeList = request.getSplitResumeResult().getInternshipExperiences() != null ?
                request.getSplitResumeResult().getInternshipExperiences().stream()
                        .map(InternshipExperience::getEndTime)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList()) : Collections.emptyList();

        boolean isEmployed = workEndTimeList.stream().anyMatch(endTime -> endTime.equals(YearMonth.of(9999, 1))) ||
                internshipEndTimeList.stream().anyMatch(endTime -> endTime.equals(YearMonth.of(9999, 1)));

        String label = isEmployed ? "在职" : "离职";

        return mapLabelsToTags(Collections.singletonList(label), labelingUtils.getTagsByCategoryId(request.getCategory().getId()));
    }

    @Override
    public List<Map<String, Integer>> processWorkExperienceRequest(LabelingRequest request) {
        validateRequest(request);

        YearMonth currentYearMonth = YearMonth.now();
        long totalMonths = 0;

        for (WorkExperience experience : request.getSplitResumeResult().getWorkExperiences()) {
            YearMonth startTime = experience.getStartTime();
            YearMonth endTime = experience.getEndTime() != null && experience.getEndTime().equals(YearMonth.of(9999, 1)) ?
                    currentYearMonth : experience.getEndTime();

            if (startTime == null || endTime == null) {
                throw new InvalidParameterException("工作经验起始时间或终止时间信息缺失");
            }

            totalMonths += ChronoUnit.MONTHS.between(startTime, endTime);
        }

        long totalYears = totalMonths / 12;

        // 确保映射逻辑正确：固定 "工作经验" + 动态年数
        String label = totalYears < 1 ? "工作经验:1年以下" : "工作经验:" + totalYears + "年";

        return mapLabelsToTags(Collections.singletonList(label), labelingUtils.getTagsByCategoryId(request.getCategory().getId()));
    }

    private void validateRequest(LabelingRequest request) {
        if (request.getSplitResumeResult() == null ||
                (request.getSplitResumeResult().getWorkExperiences() == null || request.getSplitResumeResult().getWorkExperiences().isEmpty()) &&
                        (request.getSplitResumeResult().getInternshipExperiences() == null || request.getSplitResumeResult().getInternshipExperiences().isEmpty())) {
            throw new InvalidParameterException("在职状态或工作经验信息缺失");
        }
    }

    private List<Map<String, Integer>> mapLabelsToTags(List<String> labels, List<Tag> tags) {
        List<Map<String, Integer>> result = new ArrayList<>();
        for (String label : labels) {
            for (Tag tag : tags) {
                // 修复：支持动态匹配冒号前后部分
                if (matchLabelWithTag(label, tag.getTagValue())) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(label, tag.getId());
                    result.add(map);
                }
            }
        }
        return result;
    }

    private boolean matchLabelWithTag(String label, String tagValue) {
        // 拆分标签和tag的冒号前后部分进行匹配
        String labelPrefix = label.split(":")[0];
        String tagPrefix = tagValue.split(":")[0];

        // 如果冒号前的部分相等
        if (labelPrefix.equals(tagPrefix)) {
            return true;
        }
        return false;
    }
}
